#include <bits/stdc++.h>
// 2024/12/14
// tag: 
using namespace std;

const int MAXN = 502;
int m, n, cnt, ans, grid[MAXN][MAXN], a, b, mid;
bool vis[MAXN][MAXN], waypoint[MAXN][MAXN];

int check(int x, int y){
    if (x < 1 || y < 1 || x > m || y > n)
        return 0;
    if (vis[x][y])
        return 0;
    vis[x][y] = 1;
    int result = waypoint[x][y];
    if (abs(grid[x][y] - grid[x][y - 1]) <= mid)
        result += check(x, y - 1);
    if (abs(grid[x][y] - grid[x - 1][y]) <= mid)
        result += check(x - 1, y);
    if (abs(grid[x][y] - grid[x][y + 1]) <= mid)
        result += check(x, y + 1);
    if (abs(grid[x][y] - grid[x + 1][y]) <= mid)
        result += check(x + 1, y);
    return result;
}

signed main()
{
    cin.tie(0), cout.tie(0), ios_base::sync_with_stdio(0);
    cin >> m >> n;
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            cin >> grid[i][j];
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++){
            cin >> waypoint[i][j];
            if (waypoint[i][j])
                cnt++, a = i, b = j;
        }
    int l = 0, r = 1e9;
    while (l <= r){
        mid = l + (r - l) / 2;
        if (check(a, b) == cnt)
            ans = mid, r = mid - 1;
        else
            l = mid + 1;
        memset(vis, 0, sizeof(vis));
    }
    cout << ans << endl;
    return 0;
}
